package a05_双指针法;

/**
 * <p>
 * a07_链表相交复习4
 * </p>
 *
 * @author flyduck
 * @since 2025/2/20
 */
public class a07_链表相交复习4 {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        int lengthA = 0;
        ListNode curA = headA;
        while (curA != null){
            curA = curA.next;
            lengthA++;
        }

        int lengthB = 0;
        ListNode curB = headB;
        while (curB != null){
            curB = curB.next;
            lengthB++;
        }

        curA = headA;
        curB = headB;
        if(lengthA > lengthB){
            int lengthDiff = lengthA - lengthB;
            while (lengthDiff > 0){
                curA = curA.next;
                lengthDiff--;
            }
        }else if(lengthB > lengthA){
            int lengthDiff = lengthB - lengthA;
            while (lengthDiff > 0){
                curB = curB.next;
                lengthDiff--;
            }
        }

        while (curA != null && curB != null){
            if(curA == curB){
                return curA;
            }else {
                curA = curA.next;
                curB = curB.next;
            }
        }
        return null;
    }
}
